package com.xiguaji.tiktok.task.blogger.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.dal.blogger.BloggerLogRepository;
import com.gugee.tiktok.common.model.dal.blogger.BloggerMainRepository;
import com.gugee.tiktok.common.model.dto.SlimBloggerDto;
import com.gugee.tiktok.common.model.mysql.BloggerLog;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import com.xiguaji.tiktok.task.aweme.event.RefreshAwemeCategoriesEventListener;
import com.xiguaji.tiktok.task.common.config.AppConfig;
import com.xiguaji.tiktok.task.common.job.TaskParam;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class RefreshBloggerMainCategoriesEventListener implements IEventListener<RefreshBloggerMainCategoriesEventListener.RefreshBloggerMainCategoriesEvent> {
    @Autowired
    BloggerLogRepository bloggerLogRepository;

    @Autowired
    BloggerMainRepository bloggerMainRepository;

    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;
    @Autowired
    AppConfig appConfig;
    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(RefreshBloggerMainCategoriesEvent event) {
        run(event);
    }

    public void run(RefreshBloggerMainCategoriesEvent event) {
        int bloggerLogType = BloggerLog.BloggerLogType.REFRESH_BLOGGER_MAIN_CATEGPROES.getValue();

        Optional<BloggerLog> bloggerLogOptional = bloggerLogRepository.findByLogType(bloggerLogType);
        BloggerLog bloggerLog;

        int page = 1;
        if (bloggerLogOptional.isPresent()) {
            page = (int)bloggerLogOptional.get().getCurrentBloggerId();
            bloggerLog = bloggerLogOptional.get();
        } else {
            bloggerLog = new BloggerLog();
            bloggerLog.setLogType(bloggerLogType);
//            bloggerLog.setExtValue("");
            bloggerLog.setCreateBy(event.getSource());
            bloggerLog.setUpdateBy(event.getSource());
        }

        List<SlimBloggerDto> bloggers = bloggerMainRepository.findSlimBloggersScoreAndCount(appConfig.getSysCollectFollowerCount(),(page-1)*event.taskParam.getRecords(), event.taskParam.getRecords());

        if (CollectionUtils.isEmpty(bloggers)) {
            bloggerLog.setCurrentBloggerId(1);
            bloggerLogRepository.save(bloggerLog);
            return;
        }

        bloggerLog.setCurrentBloggerId(page+1);
        bloggerLogRepository.save(bloggerLog);
        XxlJobLogger.log("当前分类的博主有:{},page={}",bloggers.size(),page);

        ForkJoinPool forkJoinPool = ThreadPoolUtils.forkJoinPool(300, "RefreshBloggerMainCategories work");

        try {
            forkJoinPool.submit(() ->
                    bloggers.parallelStream().forEach( b->{
                        long start = System.currentTimeMillis();
                        val refreshAwemeCategoriesEvent = new RefreshAwemeCategoriesEventListener.RefreshAwemeCategoriesEvent(event,b.getUid());
                        eventBusTemplate.post(refreshAwemeCategoriesEvent);
                        if((System.currentTimeMillis()-start)/1000 > 10) {
                            XxlJobLogger.log("uid={},用时:{}s",b.getUid(),(System.currentTimeMillis()-start)/1000);
                        }
                    })
            ).get();
        }catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally{
            forkJoinPool.shutdown();
        }





    }

    public static class RefreshBloggerMainCategoriesEvent extends Event {
        TaskParam taskParam;
        public RefreshBloggerMainCategoriesEvent() {
            super("RefreshBloggerMainCategoriesEvent");
        }
        public RefreshBloggerMainCategoriesEvent(TaskParam taskParam) {
            super("RefreshBloggerMainCategoriesEvent");
            this.taskParam=taskParam;
        }

    }
}
